import { findTable } from "@/api/apiJson";
import { SYS_DICT } from "@/constants/TableNameConstants";
import { functions } from "@/components/Crud/form/renderField";
import { functions as tableFunctions } from "@/components/Crud/table/renderField";
import type { PagesProps } from "@/components/Crud/utils/types";

export const initPage = async (data: PagesProps) => {
  const dict = {};
  await initColumns(data.table_config.columns, dict);
  await initColumns(data.search_config.columns, dict);
  await initColumns(data.add_config.columns, dict);
  await initColumns(data.edit_config.columns, dict);
};

/**
 * 格式化 columns
 * @param columns
 * @param dict
 */
export const initColumns = async (columns: any[], dict: object) => {
  for (const item of columns) {
    if ("dictOptions" in item) {
      //字典渲染
      if (item.dictOptions in dict) {
        item.options = dict[item.dictOptions];
      } else {
        const dictData = await findTable(SYS_DICT, {
          code: item.dictOptions
        });
        item.options = dictData[`${SYS_DICT}`].item;
        dict[item.dictOptions] = dictData[`${SYS_DICT}`].item;
      }
    }
    if ("renderField" in item) {
      const functionName = item.renderField;
      item.renderField = (value, onChange, props) => {
        return functions[functionName](value, onChange, props, item);
      };
    }
    if ("render" in item) {
      const functionName = item.render;
      item.render = (value, onChange, props) => {
        return tableFunctions[functionName](value, onChange, props);
      };
    }
  }
};
